package com.pla.googlecalendarviews;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.util.AuthenticationException;
import java.awt.Color;
import java.awt.Image;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.sql.*;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.RootPaneContainer;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

public class Utils {

  private static ClassLoader classLoader = Utils.class.getClassLoader();

  public static ImageIcon getIcon() {
    return new ImageIcon(classLoader.getResource("resources/calendar48x48.png"));
  }

  public static ImageIcon getIcon(String fileName) {
    return new ImageIcon(classLoader.getResource("resources/" + fileName));
  }

  public static Image getLogo() {
    return getIcon().getImage();
  }

  public static void main(String[] args) {
    Utils.dumpTable("calendars");
  }

  public final static String getRgbHexString(Color c) {
    String s = Integer.toHexString(c.getRGB() & 0xffffff);
    if (s.length() < 6) { // pad on left with zeros
      s = "000000".substring(0, 6 - s.length()) + s;
    }
    return '#' + s;
  }

  public static void makeDisposeOnEscapeKey(final RootPaneContainer rootPane) {
    Action action = new AbstractAction() {

      public void actionPerformed(ActionEvent actionEvent) {
        Window window = (java.awt.Window) rootPane;
        (window).dispatchEvent(new WindowEvent((window), WindowEvent.WINDOW_CLOSING));
      }
    };
    KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    rootPane.getRootPane().getActionMap().put(action, action);
    rootPane.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, action);
    rootPane.getRootPane().getInputMap(JComponent.WHEN_FOCUSED).put(stroke, action);
  }

  public static String isYes(boolean b) {
    if (b) {
      return "Y";
    } else {
      return "N";
    }
  }

  public static boolean isYes(String s) {
    if ("Y".equals(s)) {
      return true;
    } else {
      return false;
    }
  }

  public static void dumpTable(String tableName) {
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    try {
      connection = Utils.getDbConnection();
      statement = connection.createStatement();
      rs = statement.executeQuery("Select * from " + tableName);
      ResultSetMetaData rsmd = rs.getMetaData();
      int columnCount = rsmd.getColumnCount();
      System.out.println(columnCount + " columns");
      for (int i = 0; i < columnCount; i++) {
        System.out.print("\t" + rsmd.getColumnName(i + 1));
      }
      int row = 0;
      System.out.println("\n");
      while (rs.next()) {
        row++;
        for (int i = 1; i <= columnCount; i++) {
          System.out.print("\t" + rs.getString(i));
        }
        System.out.println("");
      }
      System.out.println(row + " rows");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      Utils.close(rs, statement, connection);
    }
  }

  public static boolean isCredentialsValid(String emailAddress, String password) {
    CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
    try {
      myService.setUserCredentials(emailAddress, password);
    } catch (AuthenticationException ex) {
      return false;
    }
    return true;
  }

  public static void setLookAndFeel() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
      if ("Nimbus".equals(laf.getName())) {
        try {
          UIManager.setLookAndFeel(laf.getClassName());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

  }

  public static void firstTimeCheckForTables() throws Exception {
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    try {
      connection = Utils.getDbConnection();
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "Could not get database connection. \nIs there another instance of this program running? \nThis program will exit after you press OK.\n\nError text: " + e.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE);
      e.printStackTrace();
      System.exit(0);
    }
    try {
      statement = connection.createStatement();
      rs = statement.executeQuery("Select * from accounts");
      if (rs.next()) {
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("First time in. Creating tables.");
      AccountDAO accountDAO = new AccountDAO();
      accountDAO.createTable();
      ViewDAO viewDAO = new ViewDAO();
      viewDAO.createTable();
    } finally {
      Utils.close(rs, statement, connection);
    }
  }

  public static Connection getDbConnection() throws Exception {
    String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    String dbName = "gcalviews2";
    String connectionURL = "jdbc:derby:" + dbName + ";create=true;dataEncryption=true;encryptionAlgorithm=DES/CBC/NoPadding;encryptionKey=1627384950697867";
    Class.forName(driver);
    Connection connection = DriverManager.getConnection(connectionURL);
    return connection;
  }

  public static boolean isBlank(String value) {
    if (value == null || value.trim().length() == 0) {
      return true;
    }
    return false;
  }

  public static void close(Connection connection) {
    if (connection != null) {
      try {
        connection.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void close(PreparedStatement preparedStatement) {
    if (preparedStatement != null) {
      try {
        preparedStatement.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void close(PreparedStatement preparedStatement, Connection connection) {
    close(preparedStatement);
    close(connection);
  }

  public static void close(ResultSet resultSet) {
    if (resultSet != null) {
      try {
        resultSet.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void close(ResultSet resultSet, PreparedStatement preparedStatement) {
    close(resultSet);
    close(preparedStatement);
  }

  public static void close(ResultSet resultSet, PreparedStatement preparedStatement,
          Connection connection) {
    close(resultSet);
    close(preparedStatement);
    close(connection);
  }

  public static void close(ResultSet resultSet, Statement statement) {
    close(resultSet);
    close(statement);
  }

  public static void close(ResultSet resultSet, Statement statement, Connection connection) {
    close(resultSet);
    close(statement);
    close(connection);
  }

  public static void close(Statement statement) {
    if (statement != null) {
      try {
        statement.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void close(Statement statement, Connection connection) {
    close(statement);
    close(connection);
  }
}
